<template>
	<view>
		<view class="pd-30 border-radius-25 bg-fff">
			<view id="container" style="width: 60vw; height: 60vh;"></view>
			<view class="mt-30 row gt-form-border">
				<view class="col-auto">
					<gt-input :value="location.lon" :label="$t('经度')" :placeholder="$t('经度')"></gt-input>
				</view>
				<view class="col-auto ml-30">
					<gt-input :value="location.lat" :label="$t('纬度')" :placeholder="$t('纬度')"></gt-input>
				</view>
			</view>
			<view class="row mt-30">
				<view class="btn" @click="confirm">{{ $t('确认') }}</view>
			</view>
		</view>
	</view>
</template>

<script>
	var mapobj = null;
	export default {
		name: "gt-map",
		props: {
			lon: {
				type: [Number,String],
				default: function() {
					return 0;
				}
			},
			lat: {
				type: [Number,String],
				default: function() {
					return 0;
				}
			}
		},
		data() {
			return {
				location: {
					lon: 0,
					lat: 0
				}
			}
		},
		created() {
			this.loadScript();
			if (!this.lon || !this.lat) {
				this.getLoaction();
			} else {
				this.location = {
					lon: this.lon,
					lat: this.lat,
				}
				let _this = this;
				window.mapInit = function() {
					mapobj = new AMap.Map('container', {
						viewMode: '2D', // 默认使用 2D 模式，如果希望使用带有俯仰角的 3D 模式，请设置 viewMode: '3D'
						zoom: 11, // 初始化地图层级
						center: [_this.location.lon, _this.location.lat] // 初始化地图中心点
					});
					mapobj.on('click', function(e) {
						console.log(e);
						_this.location = {
							lon: e.lnglat.lng,
							lat: e.lnglat.lat,
						};
					});
				}
			}
			
		},
		methods: {
			getLoaction() {
				let _this = this;
				this.$get({
					url: "http://ip-api.com/json",
					afterFun(r) {
						if (r.lon) _this.location.lon = r.lon;
						if (r.lat) _this.location.lat = r.lat;
						window.mapInit = function() {
							mapobj = new AMap.Map('container', {
								viewMode: '2D', // 默认使用 2D 模式，如果希望使用带有俯仰角的 3D 模式，请设置 viewMode: '3D'
								zoom: 11, // 初始化地图层级
								center: [_this.location.lon, _this.location.lat] // 初始化地图中心点
							});
							mapobj.on('click', function(e) {
								console.log(e);
								_this.location = {
									lon: e.lnglat.lng,
									lat: e.lnglat.lat,
								};
								_this.$forceUpdate();
							});
						}
					}
				})
				
			},
			loadScript() {
				let script = document.createElement('script');
				script.src = 'https://webapi.amap.com/maps?v=1.4.15&key=' + this.$var.map.key + '&callback=mapInit';
				document.body.appendChild(script);
				
			},
			confirm() {
				// this.$emit('update:lon',this.location.lon);
				// this.$emit('update:lat',this.location.lat);
				console.log(this.location)
				this.$emit('confirm', this.location);
			}
		}
	}
</script>

<style lang="scss" scoped>
</style>